<template>
  <div>
    <el-upload
      action="http://47.107.69.245/img/upload"
      :multiple="false"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
    >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="50%" :src="fileList[0].url" alt />
    </el-dialog>
  </div>
</template>
<script>
import { policy } from "@/api/oss";

export default {
  name: "singleUpload",
  props: {
    value: String
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== "") {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    fileList() {
      return [
        {
          name: this.imageName,
          url: this.imageUrl
        }
      ];
    },
    showFileList: {
      get: function() {
        return (
          this.value !== null && this.value !== "" && this.value !== undefined
        );
      },
      set: function(newValue) {}
    }
  },
  data() {
    return {
      dialogVisible: false
    };
  },
  methods: {
    emitInput(val) {
      this.$emit("input", val);
    },
    handleRemove(file, fileList) {
      this.emitInput("");
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    handleUploadSuccess(res, file) {
      this.showFileList = true;
      var el = document.createElement("html");
      el.innerHTML = res;
      let md5 = el.getElementsByTagName("h1")[0].innerHTML; // Live NodeList of your anchor elements
      this.showFileList = true;
      this.fileList.pop();
      this.fileList.push({
        name: file.name,
        url: "http://47.107.69.245/img" + "/" + md5.split(": ")[1]
      });
      this.emitInput(this.fileList[0].url);
    }
  }
};
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
.el-dialog {
  min-width: 280pt;
}
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
</style>


